#! /usr/bin/python 
#coding=UTF-8  

"""
    File:       TestLink_TestCase.py
    Brief:      Definition of TestCase on TestLink
    Author:     Xu Qiang
    Version:    1.0
    Date:       2017 - 07 - 26
"""
__author__ = """Xu Qiang"""

from HTMLTestRunner import HTMLTestRunner
from HTMLTestRunner import Testcase
from HTMLTestRunner import TestSuite

from Functional import capturePIC,GetTimeString
import datetime
import Static
import os
import time
import data.NeoCUConfig_ENG
import data.NeoCUConfig_CN
import data.NeoCUConfig
from Log import Log, LogI, LogD, LogE, LogW

class TestCase:
    def __init__( self, name, internalID, status = "not run" ):
        self.__dict__["name"] = name
        self.__dict__["internalid"] = internalID
        self.__dict__["status"] = status

    def addCustomField( self, customField, value ):
        self.__dict__[customField] = value


def AnalyzeTap(): 
    if not os.access( Static.xmlpath, os.F_OK ):
        return None
 
    import xml.dom.minidom
     
    dom = xml.dom.minidom.parse( Static.xmlpath )
    root = dom.documentElement
    allTestCasesNodess = root.childNodes
    testsuites = []
    for node in allTestCasesNodess:
        if isinstance(node,xml.dom.minidom.Element) and node.tagName=="testsuite":  
            newTestSuite = TestSuite(node.getAttribute( "name" ),"")
            for testcase in node.getElementsByTagName( "testcase" ):
                addTestcase(testcase.getAttribute( "name" ),'',getResult(testcase.getAttribute('internalid')),newTestSuite)
            newTestSuite.count()
            testsuites.append(newTestSuite)
    
    timestring = GetTimeString()
    timestring = timestring.replace(":","-")
    timestring = timestring[0:19]
    filename=Static.outputPath +'report.html'
    fp=open(filename,'wb')
    #定义测试报告
    runner=HTMLTestRunner(stream=fp,title='NeoCU UI Demo 测试报告',description='用例执行情况：')
    runner.run(datetime.datetime.now(),testsuites)
    fp.close()
    #DeleteAllTapFile()
    
def AnalyzeVMWareTap(): 
    if not os.access( Static.VMWarexmlpath, os.F_OK ):
        return None
 
    import xml.dom.minidom
     
    dom = xml.dom.minidom.parse( Static.VMWarexmlpath )
    root = dom.documentElement
    allTestCasesNodess = root.childNodes
    testsuites = []
    for node in allTestCasesNodess:
        if isinstance(node,xml.dom.minidom.Element) and node.tagName=="testsuite":  
            newTestSuite = TestSuite(node.getAttribute( "name" ),"")
            for testcase in node.getElementsByTagName( "testcase" ):
                addTestcase(testcase.getAttribute( "name" ),'',getResult(testcase.getAttribute('internalid')),newTestSuite)
            newTestSuite.count()
            testsuites.append(newTestSuite)
    
    timestring = GetTimeString()
    timestring = timestring.replace(":","-")
    timestring = timestring[0:19]
    filename=Static.outputPath +timestring+'_result.html'
    fp=open(filename,'wb')
    #定义测试报告
    runner=HTMLTestRunner(stream=fp,title='VMWareUltra Demo 测试报告',description='用例执行情况：')
    runner.run(datetime.datetime.now(),testsuites)
    fp.close()
    DeleteAllTapFile()

def addTestcase(name,dec,result,suite):
    suite.add(Testcase(name,dec,result))
  
def getResult(filepath):
    if not os.access( Static.TAPoutputPath +"NeoCU-" +filepath+".tap", os.F_OK ):
        writeTAPResult( filepath, "not ok" )
        return "error"
    file = open(Static.TAPoutputPath +"NeoCU-" +filepath+".tap",'r')
    for line in file.readlines():
        if("not run" in line):
            return "not run"
        elif("not ok" in line):
            return "fail"
        elif("ok" in line):
            return "pass"
        elif("error" in line):
            return "error"

def DeleteAllTapFile():
    allFiles = os.listdir( Static.TAPoutputPath )
    for file in allFiles:
        if ".tap" in file:
            try:
                os.remove(Static.TAPoutputPath+ file )
            except:
                pass

def getTestCaseFromXMLByInternalID( xmlFilePath, internalID ):
    if not os.access( xmlFilePath, os.F_OK ):
        return None
    result = None
    import xml.dom.minidom
    dom = xml.dom.minidom.parse( xmlFilePath )
    allTestCasesNodes = dom.getElementsByTagName( "testcase" )
    for testcase in allTestCasesNodes:
        internalid = testcase.getAttribute( "internalid" )
        if internalID == internalid:
            result = TestCase( testcase.getAttribute( "name" ), internalID, "" )
            break
        else:
            continue
    return result
    
def assertBool( first , testCaseID = None ):
    if first == True:
        LogI.write( testCaseID + " PASS " )
        writeTAPResult( testCaseID, "ok" )
    else:
        capturePIC(testCaseID +"-FAIL.jpg")
        LogI.write( testCaseID + " FAIL " )
        writeTAPResult( testCaseID, "not ok" )
           
def writeTAPResult( fileName, result ):
    fileStream = None
    if not os.access( Static.TAPoutputPath , os.F_OK ):
        os.makedirs( Static.TAPoutputPath )  
    try:
        fileStream = open(Static.TAPoutputPath + "NeoCU-" + fileName + ".tap", "w" )
    except:
        fileStream = None
    if fileStream != None:
        testCase = getTestCaseFromXMLByInternalID(Static.xmlpath, fileName)
        name = ""
        if testCase != None:
            name = testCase.name.replace( "\n", "\\n " )
        if result == "error" or result == "block" or result == "not run":
            fileStream.write( "1..1\n" )
            fileStream.write( "%s %s#\n" % ( result, name ) )
        else:
            fileStream.write( "1..1\n" )
            fileStream.write( "%s %s#\n" % ( result, name ) )
        fileStream.close()


def getInernalId(xmlFilePath):
    if not os.access( xmlFilePath, os.F_OK ):
        return None
    result = []
    import xml.dom.minidom
    dom = xml.dom.minidom.parse( xmlFilePath )
    allTestCasesNodes = dom.getElementsByTagName( "testcase" )
    for testcase in allTestCasesNodes:
        internalid = testcase.getAttribute( "internalid" )
        result.append(internalid )
    return result

def getConfigure(configName ):
    if configName in data.NeoCUConfig.NeoCU_Config:
        result = data.NeoCUConfig.NeoCU_Config[configName] 
    else:
        result = None
    return result
 
def setConfigure(configName,Value ):
    data.NeoCUConfig.NeoCU_Config[configName] =Value

def getConfigure_ENG(configName ):
    if configName in data.NeoCUConfig_ENG.NeoCU_Config:
        result = data.NeoCUConfig_ENG.NeoCU_Config[configName] 
    else:
        result = None
    return result

def setConfigure_ENG(configName,Value ):
    data.NeoCUConfig_ENG.NeoCU_Config[configName] =Value
    
def getConfigure_CN(configName ):
    if configName in data.NeoCUConfig_CN.NeoCU_Config:
        result = data.NeoCUConfig_CN.NeoCU_Config[configName] 
    else:
        result = None
    return result

def setConfigure_CN(configName,Value ):
    data.NeoCUConfig_CN.NeoCU_Config[configName] =Value

def waitMoment(sc):
    time.sleep(sc)
